package cn.vshare.controller;

import cn.vshare.entity.Coin;
import cn.vshare.entity.Trade;
import cn.vshare.service.CoinService;
import cn.vshare.service.TradeService;
import cn.vshare.util.CoinChageException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;


@RestController
public class CoinController {
    @Resource(name = "coinServiceImpl")
    private CoinService coinService;

    @Resource(name = "tradeServiceImpl")
    private TradeService tradeService;

    private Logger log = Logger.getLogger(CoinController.class);

    /**
     * 查询交易记录
     *
     * @param map
     * @return
     */
    @RequestMapping("getRecordByDynamic")
    public PageInfo<Trade> getRecordByDynamic(@RequestParam Map<String, String> map) {
        Page<Trade> page = tradeService.getTradeByDynamic(map);
        System.out.println(map.get("userId"));
        System.out.println(map.get("tradeDate1"));
        PageInfo<Trade> pageInfo = new PageInfo<>(page);
        return pageInfo;
    }

    //    打赏功能
    @RequestMapping("rewardToUser")
    public boolean rewardToUser(String myId, String userId, int count, String videoId) throws CoinChageException {
        coinService.rewardToUser(myId, userId, count, videoId);
        log.info(myId + "向" + userId + "打赏" + count);
        return true;
    }

    //查询余额
    @RequestMapping("getCoinByUserId")
    public Coin getCoinByUserId(String myId) {
        Coin coin = coinService.queryCoinMess(myId);
        System.out.println(coin);
        return coin;
    }

    @RequestMapping("toAddCoinFtl")
    public ModelAndView toAddCoinFtl() {
        return new ModelAndView("addCoin");
    }

    @RequestMapping("/countTradeMoney")
    public Map<String, Object> countTradeMoney(String condition) {
        Map<String, Object> map = new HashMap<String, Object>();
        JSONArray jsonArray = JSON.parseArray(condition);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = JSON.parseObject(jsonArray.get(i).toString());
            Integer countNum = tradeService.countTradeMoney(jsonObject);
            if (countNum == null) {
                countNum = 0;
            }
            map.put(jsonObject.get("yearRange").toString(), countNum);
        }
        return map;
    }

    @RequestMapping("/querySumCoinByVideoId")
    public int querySumCoinByVideoId(String videoId){
        return coinService.querySumCoinByVideoId(videoId);
    }


}
